package com.jstyle.jclife.fragment;

import android.content.Context;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.jstyle.jclife.R;
import com.jstyle.jclife.activity.HeartTipsActivity;
import com.jstyle.jclife.daoManager.HeartDataDaoManager;
import com.jstyle.jclife.daoManager.SleepDataDaoManager;
import com.jstyle.jclife.model.HeartData;
import com.jstyle.jclife.model.SleepData;
import com.jstyle.jclife.model.SleepShowData;
import com.jstyle.jclife.utils.ChartDataUtil;
import com.jstyle.jclife.utils.DateUtil;
import com.jstyle.jclife.utils.ResolveData;
import com.jstyle.jclife.utils.ScreenUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import lecho.lib.hellocharts.view.ColumnChartView;
import lecho.lib.hellocharts.view.LineChartView;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link SleepWeekFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SleepWeekFragment extends BaseFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.bt_sleep_week_pre)
    ImageView btSleepWeekPre;
    @BindView(R.id.bt_sleep_week_date)
    Button btSleepWeekDate;
    @BindView(R.id.bt_sleep_week_next)
    ImageView btSleepWeekNext;
    @BindView(R.id.ColumnChartView_sleep_week)
    ColumnChartView ColumnChartViewSleepWeek;
    @BindView(R.id.ColumnChartView_sleep_week_detail)
    ColumnChartView ColumnChartViewSleepWeekDetail;
    @BindView(R.id.LineChartView_sleep_week_heart)
    LineChartView LineChartViewSleepWeekHeart;
    Unbinder unbinder;
    private static final String TAG = "SleepWeekFragment";
    @BindView(R.id.tv_sleepweek_avgtime)
    TextView tvSleepweekAvgtime;
    @BindView(R.id.tv_sleepweek_lighttime)
    TextView tvSleepweekLighttime;
    @BindView(R.id.tv_sleepweek_deeptime)
    TextView tvSleepweekDeeptime;
    @BindView(R.id.bt_week_avgHr)
    Button btWeekAvgHr;
    @BindView(R.id.NestedScrollView)
    android.support.v4.widget.NestedScrollView NestedScrollView;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    String[] thisWeek;
    private OnFragmentInteractionListener mListener;
    private boolean isBusy;

    private HashMap<String, SleepShowData> markHashMap = new HashMap<>();
    private HashMap<String, Float> heartRateMap = new HashMap<>();

    public SleepWeekFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SleepWeekFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SleepWeekFragment newInstance(String param1, String param2) {
        SleepWeekFragment fragment = new SleepWeekFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_sleep_week, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void init() {
        thisWeek = DateUtil.getTodayWeek(0);
        setChartViewData();
        findData();
    }

    private void setChartViewData() {
        Typeface mFace = Typeface.createFromAsset(getActivity().getAssets(),"ROBOTO-REGULAR_2.TTF");

        ChartDataUtil.initDataChartView(ColumnChartViewSleepWeek, -0.5f, 4.5f, 6.5f, 0);
        ColumnChartViewSleepWeek.setColumnChartData(ChartDataUtil.getWeekTopColumnChart(getActivity(), thisWeek, markHashMap,mFace));
        ChartDataUtil.initDataChartView(ColumnChartViewSleepWeekDetail, -0.5f, maxSleepTime == 0 ? 4.5f : maxSleepTime * 1.2f, 6.5f, 0);
        ColumnChartViewSleepWeekDetail.setColumnChartData(ChartDataUtil.getWeekSleepColumnChart(getActivity(), thisWeek, markHashMap,mFace));
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
//        if (context instanceof OnFragmentInteractionListener) {
//            mListener = (OnFragmentInteractionListener) context;
//        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
//        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.bt_sleepHeartTips, R.id.bt_sleep_week_pre, R.id.bt_sleep_week_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_sleepHeartTips:
                startActivity(HeartTipsActivity.class, HeartTipsActivity.TipsType, HeartTipsActivity.TipsType_SleepHeart);
                break;
            case R.id.bt_sleep_week_pre:
                if (isBusy) return;
                thisWeek = DateUtil.getWeekString(thisWeek[0], DateUtil.lastWeek);
                findData();
                break;
            case R.id.bt_sleep_week_next:
                if (isBusy) return;
                thisWeek = DateUtil.getWeekString(thisWeek[6], DateUtil.nextWeek);
                findData();
                break;
        }
    }

    private void findData() {
        String showDate = DateUtil.getShowWeekDate(getActivity(), thisWeek[0]) + "-" + DateUtil.getShowWeekDate(getActivity(), thisWeek[6]);

        btSleepWeekDate.setText(showDate);
        String nowDate = DateUtil.getDefaultFormatTime(new Date());
        btSleepWeekNext.setEnabled(true);
        for (int i = 0; i < thisWeek.length - 1; i++) {
            if (thisWeek[i].equals(nowDate)) {
                btSleepWeekNext.setEnabled(false);
            }
        }
        isBusy = true;
        markHashMap.clear();
        heartRateMap.clear();
        mergeSleepData();
        //mergeHeartData();
    }

//    private void mergeHeartData() {
//        List<Observable<Integer>> observables = new ArrayList<>();
//        for (String date : thisWeek) {
//            observables.add(getHeartObservable(date));
//        }
//        Observable.merge(observables).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Integer>() {
//            @Override
//            public void onSubscribe(Disposable d) {
//
//            }
//
//            @Override
//            public void onNext(Integer value) {
//                Log.i(TAG, "onNext: " + value);
//            }
//
//            @Override
//            public void onError(Throwable e) {
//
//                Log.i(TAG, "onError: " + e.getMessage());
//            }
//
//            @Override
//            public void onComplete() {
//                setHeartChartViewData();
//
//            }
//        });
//    }

    private void setHeartChartViewData() {
        Typeface mFace = Typeface.createFromAsset(getActivity().getAssets(),"ROBOTO-REGULAR_2.TTF");

        ChartDataUtil.initDataChartView(LineChartViewSleepWeekHeart, -0.5f, 105f, 6.5f, 0);
        LineChartViewSleepWeekHeart.setLineChartData(ChartDataUtil.getSleepWeekHeartChart(getActivity(), thisWeek, heartRateMap,mFace));
        float total = 0;
        float size = 0;
        for (Map.Entry<String, Float> entry : heartRateMap.entrySet()) {
            total += entry.getValue();
            if (entry.getValue() != 0) size++;
        }
        int avg = size == 0 ? 0 : (int) (total / size);
        btWeekAvgHr.setText("Avg " + avg + "bpm");
    }


    private void mergeSleepData() {
        List<Observable<Integer>> observables = new ArrayList<>();
        for (String date : thisWeek) {
            observables.add(getDayObservable(date));
        }
        showLoadingDialog();
        Observable.merge(observables).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Integer>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Integer value) {
                Log.i(TAG, "onNext: " + value);
            }

            @Override
            public void onError(Throwable e) {
                disMissLoadingDialog();
                isBusy = false;
                Log.i(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
                disMissLoadingDialog();
                setRecycleViewData();
                setChartViewData();
                setHeartChartViewData();
                isBusy = false;
            }
        });
    }

    float maxSleepTime = 0;

    private void setRecycleViewData() {
        maxSleepTime = 0;
        float awakeTime = 0;
        float deepTime = 0;
        float lightTime = 0;
        float days = markHashMap.size();
        for (Map.Entry<String, SleepShowData> entry : markHashMap.entrySet()) {
            SleepShowData sleepShowData = entry.getValue();
            float awake = sleepShowData.getAwakeTime();
            float deep = sleepShowData.getDeepTime();
            float light = sleepShowData.getLightTime();
            maxSleepTime = Math.max(Math.max(Math.max(awake, maxSleepTime), deep), light);
            awakeTime += awake * 60f;
            deepTime += deep * 60f;
            lightTime += light * 60f;
        }
        float avgAwake = days == 0 ? 0 : awakeTime / days;
        float avgDeep = days == 0 ? 0 : deepTime / days;
        float avgLight = days == 0 ? 0 : lightTime / days;
        tvSleepweekAvgtime.setText(DateUtil.getPointSleepTime(getActivity(), avgAwake));
        tvSleepweekDeeptime.setText(DateUtil.getPointSleepTime(getActivity(), avgDeep));
        tvSleepweekLighttime.setText(DateUtil.getPointSleepTime(getActivity(), avgLight));
    }

    private Observable<Integer> getDayObservable(final String date) {
        return Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> e) throws Exception {
                String startDate = DateUtil.getTomorrowDateString(date);
                List<SleepData> sleepDataList = SleepDataDaoManager.queryData(date, startDate);
                List<HeartData> heartDataList = HeartDataDaoManager.queryData(date, startDate);
                int[] sleepData = getSleepData(sleepDataList, date);
                float[] showData = getShowSleepData(sleepData);
                getHeartRate(heartDataList, sleepData, date);
                int[] sleepLevel = new int[3];
                for (float value : showData) {
                    if (value != 0) sleepLevel[ResolveData.getSleepLevel((int) value)]++;
                }
                float deep = sleepLevel[0] * 5;
                float light = sleepLevel[1] * 5;
                float awake = sleepLevel[2] * 5;
                float total = deep + light + awake;
                int id = ResolveData.getSleepQualityLevel(deep, light);
                SleepShowData sleepShowData = new SleepShowData();
                sleepShowData.setAwakeTime(awake / 60f);
                sleepShowData.setDate(date);
                sleepShowData.setDeepTime(deep / 60f);
                sleepShowData.setLightTime(light / 60f);
                sleepShowData.setTotalTime(total / 60f);
                sleepShowData.setSleepLevel(id);
                if (id != 0) markHashMap.put(date, sleepShowData);
                e.onComplete();
            }
        }).subscribeOn(Schedulers.newThread());

    }

    private float[] getShowSleepData(int[] fiveSleepData) {
        float[] showData = new float[fiveSleepData.length];
        int length = fiveSleepData.length;
        out:
        for (int i = 0; i < length; i++) {//取5分钟的平均值
            float total = 0;
            float count = 0;
            for (int j = 0; j < 5; j++) {
                int position = i + j;
                if (position < length) {
                    int data = fiveSleepData[position];
                    if (data != -1) {
                        total += data;
                        count++;
                    }
                } else {
                    showData[i] = count == 0 ? 0 : total / count;
                    continue out;
                }

            }
            showData[i] = count == 0 ? 0 : total / count;
        }
        return showData;
    }

    private void getHeartRate(List<HeartData> heartDataList, int[] sleepData, String date) {
        List<Integer> listSleep = new ArrayList<>();
        for (int i = 0; i < sleepData.length; i++) {
            int value = sleepData[i];
            if (value != -1) {
                for (int j = 0; j < 5; j++) {
                    listSleep.add(i * 5 + j);
                }
            }
        }
        float totalHR = 0;
        float count = 0;
        int[] heartDataArray = new int[1440];//1分钟一个点。一天1440
        for (HeartData data : heartDataList) {
            String time = data.getTime();
            int value = data.getHeart();
            int startCount = DateUtil.get1MIndex(time, date + " 12:00:00");
            if (startCount >= 1440) break;
            if (listSleep.contains(startCount)) {
                if (value != 0) {
                    count++;
                    totalHR += value;
                }
            }

        }
        float avgHeart = count == 0 ? 0 : totalHR / count;
        heartRateMap.put(date, avgHeart);
    }


    private int[] getSleepData(List<SleepData> sleepDataList, String startDate) {
        int[] fiveSleepData = new int[288];//288*5分钟
        for (int i = 0; i < fiveSleepData.length; i++) {
            fiveSleepData[i] = -1;//睡眠数据0为有效数据
        }
        for (SleepData sleepData : sleepDataList) {
            String time = sleepData.getTime();
            String data = sleepData.getDateString();
            int startCount = DateUtil.get5MIndex(time, startDate + " 12:00:00");
            if (startCount >= 288) break;
            fiveSleepData[startCount] = Integer.valueOf(data);
        }
        return fiveSleepData;
    }


    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    @Override
    public void shoot() {
        super.shoot();
        ScreenUtils.shareFile(getActivity(), NestedScrollView);
    }
}
